<template>
  <div id="inDetailsvue" style="padding: 0px 20px">
    <el-row :gutter="10" type="flex" justify="start" style="font-size:12px">
      <el-col :span="1.5" style="line-height:25px;text-align: left;">
        <div id="messBox">下列服务编码还未返回预估单：{{ coding }}</div>
        <div class="colorRed">预估单未返回时请确认以下操作是否已完成：</div>
        <div class="colorRed">（1）请与地市商合岗确认对应的服务编码是否已经采购下单（选址费、赔补费、测绘费、工程签证类服务需【项目经理】跳转【商合交易系统】去下单，具体操作路径：PMS系统-【综合查询】-【选址/赔补/测绘/签证费下单】）。</div>
        <div class="colorRed">（2）如果已下单，请项目经理到商合交易系统完成收货（操作路径：我的业务/我的账户/订单管理），收货之后系统会在1小时左右推送预估单到PMS。可在订单详情页查询最新推送状态（查询路径：查看/查看订单报账）。</div>
        <div class="colorRed">（3）不需要的服务模块可通过项目设计变更删除。操作手册请见【知识管理】平台，搜索“设计变更”。</div>
        <div class="colorRed">（4）本期验工计价数量与本期验工计价金额为负数时，表示该服务为冲销验工计价；为正数时，表示该服务为新增验工计价。</div>
      </el-col>
    </el-row>
    <el-table
      ref="singleTable"
      :data="detailData"
      style="width: 100%"
      border
      :cell-style="styleBack"
      :header-cell-style="{
        background: '#F5F5F5',
        color: '#333333'
      }"
    >
      <el-table-column align="center" type="index" width="50" label="序号" />
      <el-table-column align="center" prop="serviceCode" label="服务编码" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="serviceName" label="服务名称" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="supplier" label="供应商名称" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="orderCode" label="订单编码" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="contractCode" label="合同编码" />
      <el-table-column align="center" prop="shNum" label="商合预占数" />
      <el-table-column align="center" prop="price" label="单价(元)">
        <template v-if="scope.row.serviceCode" slot-scope="scope">{{ roundingFour(scope.row.price) }}</template>
      </el-table-column>
      <el-table-column align="center" prop="shMoney" label="商合预占金额(元)">
        <template v-if="scope.row.serviceCode" slot-scope="scope">{{ rounding( scope.row.shMoney) }}</template>
      </el-table-column>
      <el-table-column align="center" prop="sumNum" label="累计验工数量">
        <template v-if="scope.row.serviceCode" slot-scope="scope">{{ roundingFour(scope.row.sumNum) }}</template>
      </el-table-column>
      <el-table-column align="center" prop="sumMoney" label="累计验工金额(元)">
        <template v-if="scope.row.serviceCode" slot-scope="scope">{{ rounding(scope.row.sumMoney) }}</template>
      </el-table-column>
      <el-table-column align="center" prop="orderState" label="订单状态">
        <template slot-scope="scope">{{ scope.row.pid =='0' ? orderStateDictionaries(scope.row.orderState):'' }}</template>
      </el-table-column>
      <el-table-column align="center" prop="surplusNum" label="可发起验工数量" />
      <el-table-column v-if="false" align="center" prop="onlybe1FLAG" label="服务数量是否只为1" />

      <!-- // IT实施验工计价 多了一个校验,  nodeNameWord =='inspection_v01' ||nodeNameWord == 'alliv02' -->
      <!-- // 购置验工计价没有校验,   -->
      <el-table-column align="center" prop="currentInspectionNum" label="本期验工数量">
        <template v-if="!scope.row.serviceCode" slot-scope="scope">
          <span v-if="nodeNameWord =='inspection_v01' ||nodeNameWord == 'alliv02'">
            <div>{{ roundingFour(scope.row.currentInspectionNum) }}</div>
          </span>
          <span v-else>
            <!-- 2024.6.17修改 -->
            <div v-if="nodeNameWord!== 'alliv01'&&nodeNameWord!== 'it_con01' ">
              <div @click="handleEdit(scope.row)">{{ roundingFour(scope.row.currentInspectionNum) }}</div>
            </div>
            <div v-else>
              <el-input v-if="scope.row.isOk && !scope.row.strVid && editor == 'true' " v-model="scope.row.currentInspectionNum" type="text" @blur="handleBlur(scope.row)" />
              <div v-else @click="handleEdit(scope.row)">{{ roundingFour(scope.row.currentInspectionNum) }}</div>
            </div>
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="currentInspectionMoney" label="本期验工金额(元)">
        <template v-if="!scope.row.serviceCode" slot-scope="scope">
          <!-- <el-input v-if="scope.row.isOk2 && scope.row.projectProGress === '100' && !scope.row.strVid" v-model="scope.row.currentInspectionMoney" type="text" @blur="handleBlurTwo(scope.row)" /> -->
          <div @click="handleEditTwo(scope.row)">{{ rounding(scope.row.currentInspectionMoney) }}</div>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="currentDeductionMoney" label="本期验工扣款金额(元)">
        <template v-if="!scope.row.serviceCode" slot-scope="scope">
          <span v-if="nodeNameWord == 'alliv02' && scope.row.isPush==0">
            <el-input v-if="scope.row.isOk4 && !scope.row.strVid" v-model="scope.row.currentDeductionMoney" type="text" @blur="handleBlurFour(scope.row)" />
            <div v-else @click="handleEditFour(scope.row)">{{ scope.row.currentDeductionMoney }}</div>
          </span>
          <span v-else>
            <div>{{ roundingFour(scope.row.currentDeductionMoney) }}</div>
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="projectProGress" label="项目进度(%)">
        <template v-if="!scope.row.serviceCode" slot-scope="scope">
          <span v-if="nodeNameWord =='inspection_v01' ||nodeNameWord == 'alliv02'">
            <div>{{ roundingFour(scope.row.projectProGress) }}</div>
          </span>
          <span v-else>
            <el-input v-if="scope.row.isOk3 && !scope.row.strVid && editor == 'true' && scope.row.isPush=='0' && (nodeNameWord !=='inspection_v01' ||nodeNameWord !== 'alliv02')" v-model="scope.row.projectProGress" type="text" @blur="handleBlurThree(scope.row)" />
            <div v-else @click="handleEditThree(scope.row)">{{ scope.row.projectProGress }}</div>
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="paymentType" :formatter="payTypeDictionaries" label="付款类型" />
      <el-table-column align="center" prop="isPush" :formatter="isPushDictionaries" label="推送状态" />
      <el-table-column v-if="(nodeNameWord == 'alliv01')||(nodeNameWord == 'it_con01'&&editor==='true') " label="操作" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.pid =='0' ">
            <el-button v-if="(scope.row.pid =='0' && scope.row.orderState =='1' && scope.row.ifAdd =='1')|| (scope.row.pid =='0' && scope.row.orderState =='1' && scope.row.ifAdd =='1' && secondarytype !='12') " type="text" size="small" @click="pushClk(scope.row)">新增</el-button>
          </span>
          <span v-if="!scope.row.serviceCode">
            <el-button v-if="scope.row.currentInspectionNum >0 && scope.row.currentInspectionMoney >0 && scope.row.paymentType =='PROGRESSING' && scope.row.isPush == 1 && scope.row.orderState =='1' && scope.row.ifShowDest == 1" type="text" size="small" @click="destroyClk(scope,scope.row)">冲销</el-button>
            <!-- {{ scope.row.isPush }}-{{ ParentNode(scope.row) }}-{{ scope.row.paymentType =='PROGRESSING' }}-{{ scope.row.PAYTYPE =='FIRST'}}-{{ scope.row.currentInspectionMoney  }} -->
            <el-button v-if="scope.row.isPush==0 && ParentNode(scope.row)=='1'" type="text" size="small" @click="delClk(scope.row)">删除</el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination
      class="pms-pagination"
      :current-page="pageParam.currentPage"
      :page-sizes="pageParam.pageSizes"
      :page-size="pageParam.pageSize"
      :layout="pageParam.layout"
      :total="pageParam.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    /> -->
  </div>
</template>
  <script>
    import { getServiceReceInspection, getConfigInfo, queryinspectionValuationDetails_all, getHaveInspection, updateInsValIT, checkIfValidatePrecision, getMaterialInfo, getCheckInsVaData } from '@/api/checkoutValuation'

    // 系统常量配置
    import SysConst from '@/common/const'
    export default {
      name: 'CheckoutValuationInDetailsvue',
      props: {
        urlForm: {
              type: Object,
              default: () => ({})
          }
      },
      data() {
        return {
          // 分页信息
          pageParam: {
            pageSize: SysConst.PAGESIZE,
            pageSizes: SysConst.PAGESIZES,
            currentPage: SysConst.CURRENT_PAGE,
            total: SysConst.TOTAL,
            layout: SysConst.TABLE_LAYOUT
          },
          itAccId: '',
          editor: '', // 是否展示操作
          prjId: '',
          fileList: [],
          coding: [], // 返回服务编码
          detailData: [], // 初始化数据
          newOldProject: '', // 0是新项目,1是老项目
          newShow: false, // 新增按钮默认不展示
          destroyShow: false, // 销毁按钮默认不展示
          delShow: false, // 删除按钮默认不展示
          fatherNodeArr: [], // 存放子节点对应的父节点
          editType: '', // 公共变量 1=新增,2=冲销
          sign: false, // 公共变量默认设置为false ---I don't know
          floataMountMax: '', // FLOATAMOUNT_MAX 上下浮动金额
          sunmNumMin: '', // 数量百分比
          oldCspectionNum: '', // 原始的本期验工数量
          oldCspectionMoney: '', // 原始的本期验工金额
          oldSumMoney: '', // 原始SumMoney
          empId: '', // 1.0 嵌套页面问题
          nodeNameWord: '',
          secondarytype: ''
        }
      },
      created() {
        this.prjId = this.urlForm.prjId
        this.newOldProject = this.urlForm.newOldProject
        this.itAccId = this.urlForm.itAccId
        this.editor = this.urlForm.editor
        this.empId = this.urlForm.empId
        this.nodeNameWord = this.urlForm.nodeNameWord
        this.secondarytype = this.urlForm.secondarytype
        console.log('初始化信息2.0', this.nodeNameWord, this.editor)
        // 公共的查询哪些服务编码没有返回预估单
        getServiceReceInspection({ prjId: this.prjId }).then(res => {
            if (res.code === '200' && res.data.length > 0) {
                res.data.map((v) => {
                    this.coding.push(v)
                })
                this.coding = this.coding.join(',') + '。'
            } else if (res.data.length === 0) {
              this.coding = '无。'
            } else {
              console.log('[]')
            }
        })
        // 获取验工计价配置信息
        getConfigInfo({ prjId: this.prjId }).then(res => {
            if (res.code === '200') {
              this.floataMountMax = Number(res.data.FLOATAMOUNT_MAX) // FLOATAMOUNT_MAX 上下浮动金额
              this.sunmNumMin = Number(res.data.SUMNUM_MIN) // 数量百分比
              // this.flowNumUMax = Number(res.data.FLOWNUM_MAX) // 流程次数
            }
        })
        this.listData()
      },
      methods: {
        // 初始化列表数据
        async listData() {
          const { code, data } = await queryinspectionValuationDetails_all({ prjId: this.prjId })
          if (code === '200') {
            this.detailData = data
            data.map(v => {
                if (v.pid === '0') {
                  this.fatherNodeArr.push(v) // 获取所有父节点
                }
            })
          }
        },
        // 获取关联父子数据的orderState
        ParentNode(e) {
          var fuDataVal = ''
          this.fatherNodeArr.map(fuVal => {
              if (fuVal.vid === e.pid) {
                fuDataVal = fuVal.orderState
              }
          })
          return fuDataVal
        },
        // 补0
        rounding(value) {
          return this.newOldProject === '1' ? Number(value).toFixed(2) : value
        },
        roundingFour(value) {
          return this.newOldProject === '1' ? Number(value).toFixed(4) : value
        },
        // 改变可修改的字段颜色
        styleBack(row) {
          if (row.row.isPush === '0' && this.nodeNameWord !== 'inspection_v01' && this.nodeNameWord !== 'alliv02') {
            if (row.columnIndex === 13 || row.columnIndex === 16) {
              return { backgroundColor: '#fceee2' }
            }
          }
          if (row.row.isPush === '0' && row.row.projectProGress === '100' && this.nodeNameWord !== 'alliv02') {
            if (row.columnIndex === 14) {
              return { backgroundColor: '#fceee2' }
            }
          }
          if ((this.nodeNameWord === 'inspection_v01' || this.nodeNameWord === 'alliv02') && this.nodeNameWord === 'alliv02' && row.row.isPush === '0') {
              if (row.columnIndex === 15) {
                console.log('执行啊1')
                return { backgroundColor: '#fceee2' }
              }
          }
        },
        farmatNum(Num) { // 四舍五入保留4位小数
          var pum = 0
          var value = ''
          if (Num < 0) {
            pum = -Num
          } else {
            pum = Num
          }
          value = Math.round(Number(pum) * Math.pow(10, 4)) / Math.pow(10, 4)
          if (Num < 0) {
            return -value
          } else {
            return value
          }
        },
        farmatMoney(money) { // 四舍五入保留2位小数
              var pum = 0
              var value = ''
              if (money < 0) {
                  pum = -money
              } else {
                  pum = money
              }
              value = Math.round(pum * Math.pow(10, 2)) / Math.pow(10, 2)
              // if (this.newOldProject === '0') {
              //   value = Math.round(pum * Math.pow(10, 9)) / Math.pow(10, 9)
              // } else {
              //   value = Number(pum)
              // }
              if (money < 0) {
                  return -value
              } else {
                  return value
              }
        },
        farmatDeductionMoney(money) { // 四舍五入保留2位小数
              var pum = 0
          if (money < 0) {
            pum = -money
          } else {
            pum = money
          }
              var value = Math.round(pum * Math.pow(10, 2)) / Math.pow(10, 2)
          return -value
        },
        // 推送状态字典转换
        isPushDictionaries(row) {
          switch (row.isPush) {
              case '0':
              return '未推送'
              case '1':
              return '已推送'
              case '2':
              return '推送超时'
              case '3':
              return '部分推送'
              default:
              break
          }
        },
        // 付款类型字典转换
        payTypeDictionaries(row) {
          switch (row.paymentType) {
              case 'FIRST':
              return '首付款（含安全生产费）'
              case 'PROGRESSING':
              return '进度款'
              case 'LOSS':
              return '损失款'
              default:
              break
          }
        },
        // 订单状态字典转换
        orderStateDictionaries(row) {
          switch (row) {
              case '1':
              return '有效'
              case '0':
              return '无效'
              case '-1':
              return '冻结'
              default:
              break
          }
        },
        async pushClkrepairOne(row){
          if ((row.shNum - row.sumNum) === 0) {
            this.$message({
                message: '当前累计验工计价数量等于商合预占数量,不支持新增操作!',
                type: 'warning'
            })
            return Promise.reject()

          }
          if ((row.shMoney - row.sumMoney) === 0) {
            this.$message({
                message: '当前累计验工计价金额等于商合预金额,不支持新增操作!',
                type: 'warning'
            })
            return Promise.reject()
          }
        },
        async pushClkrepairTwo(getHaveInspections){
          if (getHaveInspections.code === '200'&&getHaveInspections.data.length > 0) {
            this.$message({
                message: '当前验收阶段已存在未推送商合的验工计价信息，请删掉重新做验工计价！',
                type: 'warning'
            })
            return Promise.reject()
          }
        },
        async pushClkrepairThree(data){
          const updateResult = await updateInsValIT(data)
            if (updateResult.code === '200') {
              if (updateResult.message === '操作成功') {
                    this.listData()
                    this.$message({
                        message: '新增成功',
                        type: 'success'
                    })
              } else {
                this.$message({
                    message: '新增失败',
                    type: 'error'
                })
              }
            }
        },
        // 新增事件
        async pushClk(row) {
          var pId = row.vid
          var prjId = row.prjId
          var subPrjId = row.subPrjId
          var serviceCode = row.serviceCode
          var siteId = row.siteId
          var currentInspectionMoney = this.farmatMoney(row.shMoney - row.sumMoney)
          var currentInspectionNum = row.surplusNum
          var projectProgress = '100'
          var sumNum = row.shNum // 新增累计数量直接等于商合预占数
          var sumMoney = row.shMoney // 新增累计金额直接等于商合预金额
          var taxrate = row.taxrate // 税率
          var onlyBe1Flag = row.onlybe1flag
          var purchaseMode = row.purchaseMode
          var orderDetailId = row.orderDetailId
          // 新增的数据
          this.editType = '1'
          await this.pushClkrepairOne(row)
          var vId = row.vid // 数据ID
          var flag = false
          const getHaveInspections = await getHaveInspection({ itAccId: this.itAccId, vId: vId })
          await this.pushClkrepairTwo(getHaveInspections)
          var fuZiArr = []
          this.detailData.map(v => {
            if (v.pid === this.fatherNodeArr[0].vid) {
              fuZiArr.push(v)
            }
          })
          console.log(fuZiArr, 'fuZiArr')
          for (var i = 0; i < fuZiArr.length; i++) { // 进度100 且 付款类型为首付款的时候 sign =true
            if (fuZiArr[i].projectProGress === '100' && fuZiArr[i].payType === 'PROGRESSING') {
              this.sign = true
            }
          }
          var inspectionTax = Number(currentInspectionMoney) * Number(taxrate) // 验工计价税额 = 本期验工金额*税率
              inspectionTax = this.farmatMoney(inspectionTax)
          const inspectionTaxAmount = this.farmatMoney(Number(currentInspectionMoney) + Number(inspectionTax)) // 含税验工计价总金额 = 本期验工金额 + 验工计价税额
          var data = { pId: pId, prjId: prjId, subPrjId: subPrjId, onlyBe1Flag: onlyBe1Flag, siteId: siteId, serviceCode: serviceCode,
                currentInspectionNum: currentInspectionNum, currentInspectionMoney: currentInspectionMoney, sumMoney: sumMoney,
                sumNum: sumNum, projectProgress: projectProgress, inspectionTax: inspectionTax, inspectionTaxAmount: inspectionTaxAmount,
                orderDetailId: orderDetailId, purchaseMode: purchaseMode, payType: 'PROGRESSING', flag: '1', itAccId: this.itAccId, empId: this.empId
              }
              console.log(data, 'row')
            await this.pushClkrepairThree(data)
        },
        // 冲销事件
        async destroyClk(scope, row) {
          var fuDataVal = ''
          this.detailData.map(fuVal => {
            if (fuVal.vid === row.pid) {
              fuDataVal = fuVal
            }
          })
          console.log(row, row.paymentType, 'rowrowrow')
          var pId = row.pid
          var vId = row.vid
          var prjId = row.prjId
          var subPrjId = row.subPrjId
          var serviceCode = fuDataVal.serviceCode
          var siteId = fuDataVal.siteId
          var currentInspectionMoney = -row.currentInspectionMoney
          var currentInspectionNum = -Number(row.currentInspectionNum)
          var projectProgress = row.projectProGress
          var sumNum = this.farmatNum(Number(fuDataVal.sumNum) - Number(row.currentInspectionNum)) // 冲销累计数量直接等于累计数量 -当前数量
          var sumMoney = this.farmatMoney(Number(fuDataVal.sumMoney) - Number(row.currentInspectionMoney)) // 冲销累计金额直接等于累计金额 -当前金额
          var taxrate = fuDataVal.taxrate // 税率
          var onlyBe1Flag = fuDataVal.onlybe1flag
          var purchaseMode = fuDataVal.purchaseMode
          var orderDetailId = fuDataVal.orderDetailId
          this.editType = '2'
          var fuZiArr = []
          this.detailData.map(v => {
            if (v.pid === this.fatherNodeArr[0].vid) {
              fuZiArr.push(v)
            }
          })
          console.log(fuZiArr, 'fuZiArr')
          for (var i = 0; i < fuZiArr.length; i++) { // 进度100 且 付款类型为首付款的时候 sign =true
            if (fuZiArr[i].projectProGress === '100' && fuZiArr[i].payType === 'PROGRESSING') {
              this.sign = true
            }
          }
          var inspectionTax = Number(currentInspectionMoney) * Number(taxrate) // 验工计价税额 = 本期验工金额*税率
              inspectionTax = this.farmatMoney(inspectionTax)
          const inspectionTaxAmount = this.farmatMoney(Number(currentInspectionMoney) + Number(inspectionTax)) // 含税验工计价总金额 = 本期验工金额 + 验工计价税额
          var data = { pId: pId, prjId: prjId, subPrjId: subPrjId, onlyBe1Flag: onlyBe1Flag, siteId: siteId, serviceCode: serviceCode,
                currentInspectionNum: currentInspectionNum, currentInspectionMoney: currentInspectionMoney, sumMoney: sumMoney,
                sumNum: sumNum, projectProgress: projectProgress, inspectionTax: inspectionTax, inspectionTaxAmount: inspectionTaxAmount,
                orderDetailId: orderDetailId, purchaseMode: purchaseMode, payType: row.paymentType, flag: '1', ifShowDest: 2, strVid: vId, itAccId: this.itAccId, empId: this.empId
              }
              console.log(data, 'row')
            const updateResult = await updateInsValIT(data)
            if (updateResult.code === '200') {
              if (updateResult.message === '操作成功') {
                    this.listData()
                    this.$message({
                        message: '冲销成功',
                        type: 'success'
                    })
              } else {
                this.$message({
                    message: '冲销失败',
                    type: 'error'
                })
              }
            }
        },
        // 删除事件
        delClk(row) {
          var record = row
          var parentNode = ''
          this.fatherNodeArr.map(fuVal => {
              if (fuVal.vid === row.pid) {
                // fuDataVal = fuVal.orderState
                parentNode = fuVal
              }
          })
          var currentInspectionNum = record.currentInspectionNum
          var currentInspectionMoney = record.currentInspectionMoney
          var sumNum = parentNode.sumNum // 该订单累计验工数量
          var sumMoney = parentNode.sumMoney // 该订单累计验工金额
          var diffNum = Number(sumNum) - Number(currentInspectionNum) // -----------------------------------------不明白什么意思
          var diffMoney = Number(sumMoney) - Number(currentInspectionMoney)
          if (parentNode.onlybe1flag === 'N' && diffNum < 0) {
            this.$message({
                message: '本订单的累计验工数量应大于等于0！',
                type: 'warning'
            })
            return
          }
          if (parentNode.onlybe1flag === 'Y' && diffMoney < 0) {
            this.$message({
                message: '本订单的累计验工金额应大于等于0！',
                type: 'warning'
            })
            return
          }
          this.$confirm('确认删除该明细？', '删除提醒', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
              cancelButtonClass: 'pms-zr-button',
              confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
          }).then(async() => {
              // treegrid.loading("删除中，请稍后......")
              var ifShowDest = ''
              var strVid = ''
              if (record.strVid) {
                  ifShowDest = 1
                  strVid = record.strVid
              } else {
                  ifShowDest = 2
              }
              const onlyBe1Flag = parentNode.onlybe1flag
              const pId = record.pid
              const vId = record.vid
              const currentInspectionNums = record.currentInspectionNum
              const currentInspectionMoneys = record.currentInspectionMoney
              const serviceCode = parentNode.serviceCode
              const prjId = parentNode.prjId
              const subPrjId = parentNode.subPrjId
              const data = { onlyBe1Flag: onlyBe1Flag, currentInspectionNum: currentInspectionNums,
                            currentInspectionMoney: currentInspectionMoneys,
                            serviceCode: serviceCode, prjId: prjId, subPrjId: subPrjId,
                            pId: pId, vId: vId, flag: '3', ifShowDest: ifShowDest, strVid: strVid, empId: this.empId
                            }
                            const updateResult = await updateInsValIT(data)
                            if (updateResult.code === '200') {
                              this.listData()
                              this.$message({
                                  message: '删除成功',
                                  type: 'success'
                              })
                            }
          })
        },
        handleEdit(row, event, column) {
          if (Number(row.isPush) === 0) {
            this.$set(row, 'isOk', true)
          }
          this.oldCspectionNum = row.currentInspectionNum
          this.oldCspectionMoney = row.currentInspectionMoney
        },
        handleEditTwo(row, event, column) {
        //  if (Number(row.isPush) === 0) {
        //     this.$set(row, 'isOk2', true)
        //   }
          // this.oldCspectionNum = row.currentInspectionNum
          // this.oldCspectionMoney = row.currentInspectionMoney
        },
        handleEditThree(row, event, column) {
          if (Number(row.isPush) === 0) {
            this.$set(row, 'isOk3', true)
          }
          var fuDataVal = ''
          this.fatherNodeArr.map(fuVal => {
            if (fuVal.vid === row.pid) {
              fuDataVal = fuVal
            }
          })
          this.oldSumMoney = fuDataVal.sumMoney
        },
        handleEditFour(row, event, column) {
          if (Number(row.isPush) === 0) {
            this.$set(row, 'isOk4', true)
          }
          var fuDataVal = ''
          this.fatherNodeArr.map(fuVal => {
            if (fuVal.vid === row.pid) {
              fuDataVal = fuVal
            }
          })
          this.oldSumMoney = fuDataVal.sumMoney
        },
        handleBlur(row, event, column) {
          var fuDataVal = ''
          this.fatherNodeArr.map(fuVal => {
            if (fuVal.vid === row.pid) {
              fuDataVal = fuVal
            }
          })
          this.$set(row, 'isOk', false)
          row.currentInspectionNum = this.farmatNum(row.currentInspectionNum)
          row.currentInspectionMoney = this.farmatMoney(Number(row.currentInspectionNum) * Number(fuDataVal.price))
          fuDataVal.sumNum = this.farmatNum(fuDataVal.sumNum - Number(this.oldCspectionNum) + Number(row.currentInspectionNum))
          fuDataVal.sumMoney = this.farmatMoney(Number(fuDataVal.sumMoney) - Number(this.oldCspectionMoney) + Number(row.currentInspectionMoney))
          fuDataVal.surplusNum = this.farmatNum(fuDataVal.shNum - fuDataVal.sumNum)
          this.onCellValidation(row)
        },
        // handleBlurTwo(row, event, column) {
        //   var fuDataVal = ''
        //   this.fatherNodeArr.map(fuVal => {
        //     if (fuVal.vid === row.pid) {
        //       fuDataVal = fuVal
        //     }
        //   })
        //   this.$set(row, 'isOk2', false)
        //   row.currentInspectionMoney = this.farmatMoney(row.currentInspectionMoney)
        //   fuDataVal.sumMoney = this.farmatMoney(Number(fuDataVal.sumMoney) - Number(this.oldCspectionMoney) + Number(row.currentInspectionMoney))
        //   this.onCellValidation(row)
        // },
        handleBlurThree(row, event, column) {
          this.$set(row, 'isOk3', false)
          this.onCellValidation(row)
        },
        handleBlurFour(row, event, column) {
          this.$set(row, 'isOk4', false)
          this.onCellValidation(row, 'isOk4')
        },
        // 失去 焦点调用的事件
        onCellValidation(row, isOk) {
          var fuDataVal = ''
          this.fatherNodeArr.map(fuVal => {
            if (fuVal.vid === row.pid) {
              fuDataVal = fuVal
            }
          })
          var record = row
          // var price = record.price
          // var currentTinSpectionNum = this.farmatNum(record.currentInspectionNum)
          // var currentinSpectionMoney = this.farmatMoney(currentTinSpectionNum * price)
          // var sumNum = this.farmatNum(Number(fuDataVal.sumNum) - Number(this.oldCspectionNum) + Number(row.currentInspectionNum))
          // var sumMoney = this.farmatMoney(Number(fuDataVal.sumMoney) - Number(this.oldCspectionMoney) + Number(row.currentInspectionMoney))
          // var totalNum = this.farmatNum(Number(sumNum) + Number(currentTinSpectionNum))
          var shNum = fuDataVal.shNum
          var shMoney = fuDataVal.shMoney
          var projectProGress = record.projectProGress
          if (isNaN(record.currentInspectionNum) || isNaN(record.currentInspectionMoney)) {
              this.$message({
                message: '非法字符!',
                type: 'warning'
              })
                this.isValid = false
                return
              } else {
                this.isValid = true
              }
          if (Number(record.currentInspectionNum) <= 0) {
              this.$message({
                  message: '本期验工数量必须填写正数!',
                  type: 'warning'
                })
                this.isValid = false
                return
              } else {
                this.isValid = true
              }
          if (Number(row.currentTinSpectionNum) > shNum) {
              this.$message({
                  message: '当前预估单的累计验工数量应小于等于商合预占数!',
                  type: 'warning'
                })
                this.isValid = false
                return
              } else {
                this.isValid = true
              }
          if (Number(row.currentInspectionMoney) > shMoney) { // 原始的本期验工金额
            this.$message({
              message: '当前预估单的累计验工金额应小于等于商合预占金额！',
              type: 'warning'
            })
            return
          }
          if (projectProGress > 100 || projectProGress < 0) {
            this.$message({
                message: '验工计价进度输入数字必须在0-100之间',
                type: 'warning'
              })
              return
          }
          this.saveData(row, isOk)
        },
        async saveDatarepairOne(row, isOk,currentInspectionMoney,sumMoney) {
          let backsumMoney = sumMoney
          if (row.payType !== 'LOSS' && isOk === 'isOk4') {
            backsumMoney = this.farmatMoney(currentInspectionMoney - Math.abs(row.currentDeductionMoney))
          }
          return backsumMoney
        },
        async saveDatarepairTwo(checkIfValidateRes,serviceCode,currentInspectionNum,shNum){
          if (+checkIfValidateRes.code === 200) {
            if (checkIfValidateRes.data === '0') {
              // 精度校验
              var AllspuUnitAcc = '' // 储存获取的精度
              var yuzhanJingdu = '' // 储存预占数数量精度
              const obj1 = {
                materialCode: serviceCode
              }
              const jingDuData = await getMaterialInfo(obj1)
              if (jingDuData.code === '200') {
                AllspuUnitAcc = await this.saveDatarepairFive(jingDuData,AllspuUnitAcc)
              }
              var shuliang = currentInspectionNum.toString().replace('.', ',')
              var shuliangArr = shuliang.split(',')

              var shJingdu = shNum.toString().replace('.', ',') // 商合预占数精度
              var shJingduArr = shJingdu.split(',')
              yuzhanJingdu = await this.saveDatarepairFour(yuzhanJingdu,shuliangArr,shJingduArr)
              // var shuliang = currentInspectionNum.toString().replace('.', ',')
              // var shuliangArr = shuliang.split(',')
              await this.saveDatarepairThree(shuliangArr,jingDuData,AllspuUnitAcc,yuzhanJingdu)
            }
          }
        },
        async saveDatarepairThree(shuliangArr,jingDuData,AllspuUnitAcc,yuzhanJingdu){
          if (shuliangArr.length === 2 && shuliangArr[1].length > Number(jingDuData.data.spuUnitAcc)) { // 有小数时候, 小数精度 大于 预占数精度时候
            this.$message({
              message: '本期验工数量精度填写不正确，本期验工数量精度为' + AllspuUnitAcc + '，物料精度为' + yuzhanJingdu,
              type: 'warning'
            })
            return Promise.reject()
          }
        },
        async saveDatarepairFour(yuzhanJingdu,shuliangArr,shJingduArr){
          let backyuzhanJingdu = yuzhanJingdu
          if (shJingduArr.length === 1) {
            backyuzhanJingdu = '整数'
          }
          if (shJingduArr.length === 2) {
            backyuzhanJingdu = shuliangArr[1].length + '位小数'
          }
          return backyuzhanJingdu
        },
        async saveDatarepairFive(jingDuData,AllspuUnitAcc){
          let backAllspuUnitAcc= AllspuUnitAcc
          if (jingDuData.data.spuUnitAcc === '0') {
            backAllspuUnitAcc = '整数'
          } else {
            backAllspuUnitAcc = jingDuData.data.spuUnitAcc + '位小数'
          }
          return backAllspuUnitAcc
        },
        async saveDatarepairSix(currentInspectionMoney,currentInspectionNum,sumNum){
          if (currentInspectionMoney < 0 || currentInspectionNum < 0) {
              this.$message({
                  message: '当前为新增验工计价，请填写正数验工计价！',
                  type: 'warning'
              })
              return Promise.reject()
          } 
           if (currentInspectionMoney < 0) {
              this.$message({
                  message: '当前为新增验工计价，请填写正数验工计价！',
                  type: 'warning'
              })
              return Promise.reject()
          }
          if (sumNum < 0) {
              this.$message({
                      message: '当前预估单的累计验工数量应大于等于0！',
                      type: 'warning'
                  })
              return Promise.reject()
          }
        },
        async saveDatarepairSeven(currentInspectionMoney,shMoney,sumMoney){
          if (Number(currentInspectionMoney) > Number(shMoney)) {
              this.$message({
                      message: '本期验工金额应小于商合预占金额',
                      type: 'warning'
                  })
              return Promise.reject()
          }
          if (Number(sumMoney) > Number(shMoney) || Number(sumMoney) < 0) {
              this.$message({
                  message: '当前预估单的累计验工金额应小于等于商合预占及金额且大于等于0！',
                  type: 'warning'
              })
              return Promise.reject()
          }
        },
        async saveDatarepairEight(allServiceShNumSum,allServiceTServListAmount,allServiceTServListAdjAmount){
          return allServiceShNumSum < allServiceTServListAmount ? (allServiceShNumSum < allServiceTServListAdjAmount ? allServiceShNumSum : allServiceTServListAdjAmount) : (allServiceTServListAmount < allServiceTServListAdjAmount ? allServiceTServListAmount : allServiceTServListAdjAmount)
        },
        async saveDatarepairNine(allServiceShNumSum,allServiceTServListAmount,minSumNum){
          let backminSumNum =minSumNum
          if (allServiceShNumSum > allServiceTServListAmount) { // 服务所有订单下商合预占数量的和 大于设计表服务数量
            backminSumNum = allServiceTServListAmount
          } else {
            backminSumNum = allServiceShNumSum
          }
          return backminSumNum
        },
        async saveDatarepairTen(allServiceSumNum,minSumNum){
          if (allServiceSumNum > minSumNum) {
                this.$message({
                    message: '当前服务编码所有预估单累计验工数量应小于等于本服务所有预估单的累计商合预占数或设计清单数量！',
                    type: 'warning'
                })
                return Promise.reject()
            }
            if (allServiceSumNum < 0) {
              this.$message({
                    message: '本服务所有预估单的累计验工数量应大于等于0！',
                    type: 'warning'
                })
                return Promise.reject()
            }
        },
        async saveDatarepairEleve(sumMoney,shMoney,projectProgress,sumNum,shNum){
          if (Number(sumMoney) === Number(shMoney) && projectProgress !== '100') {
            this.$message({
                  message: '当前预估单累计验工金额等于商合预占金额，需要将项目进度填为100！',
                  type: 'warning'
              })
            return Promise.reject()
          }
          if (Number(sumNum) === Number(shNum) && projectProgress !== '100') {
            this.$message({
                  message: '当前预估单累计验工数量等于商合预占数量，需要将项目进度填为100！',
                  type: 'warning'
              })
            return Promise.reject()
          }
        },
        async saveDatarepairTweleve(data){
          const updateResult = await updateInsValIT(data)
            if (updateResult.code === '200') {
                this.listData()
                this.$message({
                    message: '保存成功',
                    type: 'success'
                })
            } else {
              this.$message({
                    message: '保存失败',
                    type: 'error'
                })
            }
        },
        // 失去焦点后保存校验 &&  保存事件
        async saveData(row, isOk) {
          var fuDataVal = ''
          this.detailData.map(fuVal => {
            if (fuVal.vid === row.pid) {
              fuDataVal = fuVal
            }
          })
          var pId = row.pid
          var vId = row.vid
          var prjId = row.prjId
          var subPrjId = row.subPrjId
          var serviceCode = fuDataVal.serviceCode
          var siteId = fuDataVal.siteId
          var currentInspectionMoney = row.currentInspectionMoney
          var currentInspectionNum = row.currentInspectionNum
          var projectProgress = row.projectProGress
          var shMoney = fuDataVal.shMoney
          var shNum = fuDataVal.shNum
          var sumNum = fuDataVal.sumNum
          var sumMoney = fuDataVal.sumMoney
          sumMoney = await this.saveDatarepairOne(row, isOk,currentInspectionMoney,sumMoney)
          var taxrate = fuDataVal.taxrate // 税率
          var onlyBe1Flag = fuDataVal.onlybe1flag
          var purchaseMode = fuDataVal.purchaseMode
          var orderDetailId = fuDataVal.orderDetailId
          var currentDeductionMoney = row.currentDeductionMoney
          var payType = row.payType
          const checkIfValidateRes = await checkIfValidatePrecision(this.prjId)
          await this.saveDatarepairTwo(checkIfValidateRes,serviceCode,currentInspectionNum,shNum)
          await this.saveDatarepairSix(currentInspectionMoney,currentInspectionNum,sumNum)
          await this.saveDatarepairSeven(currentInspectionMoney,shMoney,sumMoney)
          // 保存验工计价通用校验 ↓
          var flag = false
          // var allServiceSumMoney = 0 // 服务所有订单下累计验工金额
          var allServiceSumNum = 0 // 服务所有订单下累计验工数量
          // var allServiceShMoneySum = 0 // 服务所有订单下商合预占金额的和
          var allServiceShNumSum = 0 // 服务所有订单下商合预占数量的和
          // var allServiceTServListEquipSum = 0 // 设计表服务及金额
          var allServiceTServListAmount = 0 // 设计表服务数量
          var allServiceTServListAdjAmount = 0 // 设计变更表服务数量
          // var allServiceTServListAdjEquipSum = 0 // 设计变更表服务及金额
          var allSupplementNum = 0 // 在建工程损失补采数量
          var minSumNum = 0
          const obj = {
            serviceCode: serviceCode,
            subPrjId: subPrjId,
            prjId: prjId,
            type: '0'
          }
          const gCheckData = await getCheckInsVaData(obj)
          if (gCheckData.code === '200') {
            // allServiceSumMoney = this.farmatMoney(Number(gCheckData.data.currentInspectionSum.CURRENT_INSPECTION_MONEY_SUM) + Number(currentInspectionMoney))
            allServiceSumNum = this.farmatNum(Number(gCheckData.data.currentInspectionSum.CURRENT_INSPECTION_NUM_SUM) + Number(currentInspectionNum)) // 所有订单累计数量+当前所填本期验工数量
            //  allServiceShMoneySum = gCheckData.data.shSum.SH_MONEY_SUM
            allServiceShNumSum = gCheckData.data.shSum.SH_NUM_SUM
            // allServiceTServListEquipSum = gCheckData.data.serListSum[0].SJ_MONEY
            allServiceTServListAmount = gCheckData.data.serListSum.SJ_AMOUNT
            // if (allServiceTServListAmount === null) {
            //   console.log('服务设计表中无该条服务数据')
            // }
            if (gCheckData.data.serListAdjSum.SJ_ADJ_AMOUNT || gCheckData.data.serListAdjSum.SJ_ADJ_MONEY) { // 设计变更表中有数据已发生设计变更  在商合、设计、设计变更 金额中取最小值
              // 设计表服务预算合价+在建工程损失金额
              // allServiceTServListAdjEquipSum = gCheckData.data.serListAdjSum.SJ_ADJ_MONEY
              allServiceTServListAdjAmount = gCheckData.data.serListAdjSum.SJ_ADJ_AMOUNT
              // if (allServiceTServListAdjAmount === null) {
              //     console.log('服务设计变更表中无该条服务数据')
              //   //  console.log(allServiceSumMoney, allServiceShMoneySum, allServiceTServListEquipSum, allServiceTServListAdjEquipSum)
              // }
              // 设计表服务建设数量+在建工程损失数量
              allServiceTServListAdjAmount = gCheckData.data.serListAdjSum.SJ_ADJ_AMOUNT + allSupplementNum
              // 商合、设计+补采、设计变更+补采取最小值
              minSumNum = await this.saveDatarepairEight(allServiceShNumSum,allServiceTServListAmount,allServiceTServListAdjAmount)
            } else {
              minSumNum= await this.saveDatarepairNine(allServiceShNumSum,allServiceTServListAmount,minSumNum)
            }
           await this.saveDatarepairTen(allServiceSumNum,minSumNum)
          }
       
          await this.saveDatarepairEleve(sumMoney,shMoney,projectProgress,sumNum,shNum)
          
          // if (allServiceSumNum === allServiceTServListAmount && sumNum !== '0' && projectProgress !== '100') {
          //   this.$message({
          //         message: '当前服务编码所有预估单累计验工数量等于设计方案中数量，需要将项目进度填为100！',
          //         type: 'warning'
          //     })
          //     return
          // }
          var inspectionTax = (this.farmatMoney(currentInspectionMoney) - this.farmatMoney(currentDeductionMoney)) * Number(taxrate) // 验工计价税额 = 本期验工金额*税率
              inspectionTax = this.farmatMoney(inspectionTax)
          var inspectionTaxAmount = this.farmatMoney(Number(currentInspectionMoney) + Number(inspectionTax)) // 含税验工计价总金额 = 本期验工金额 + 验工计价税额
          var data = { pId: pId, prjId: prjId, subPrjId: subPrjId, onlyBe1Flag: onlyBe1Flag, siteId: siteId, serviceCode: serviceCode,
                currentInspectionNum: currentInspectionNum, currentInspectionMoney: currentInspectionMoney, sumMoney: sumMoney,
                sumNum: sumNum, projectProgress: projectProgress, inspectionTax: inspectionTax, inspectionTaxAmount: inspectionTaxAmount, currentDeductionMoney: currentDeductionMoney,
                orderDetailId: orderDetailId, purchaseMode: purchaseMode, payType: payType, flag: '2', vid: vId, empId: this.empId
              }
              // data: {
              //   	"vId":vId,"pId":pId,"currentInspectionNum":currentInspectionNum,"currentInspectionMoney":currentInspectionMoney,
              //   	"projectProgress":projectProgress,"onlyBe1Flag":onlyBe1Flag,"sumNum":sumNum,"sumMoney":sumMoney,
              //   	"serviceCode":serviceCode,"prjId":prjId,"subPrjId":subPrjId,"inspectionTax":inspectionTax,"inspectionTaxAmount":inspectionTaxAmount,"flag":"2",
              //   	"currentDeductionMoney":currentDeductionMoney,"deductiontax":deductiontax,"deductiontaxamount":deductiontaxamount
              //   },
           await this.saveDatarepairTweleve(data)
        },
        // ****////
        // 切换每页显示条数时
        handleSizeChange(val) {
          this.pageSize = val
          console.log('每页' + val + '条')
          // 代码逻辑
        },
        // 点击页码时
        handleCurrentChange(val) {
          this.currentPageValue = val
          console.log('当前页' + val)
          // 代码逻辑
        },
        // 点击‘确定’按钮时
        handleCurrentClick() {
          // 判断输入的是否为正整数
          if ((/(^[1-9]\d*$)/.test(this.currentPageValue))) {
            const maxPageNum = Math.ceil(this.pageTotal / this.pageSize)
            if (this.currentPageValue > maxPageNum) {
              this.currentPage = maxPageNum
              this.currentPageValue = maxPageNum
            } else {
              this.currentPage = parseFloat(this.currentPageValue)
            }
            console.log('当前页' + this.currentPageValue)
            // 代码逻辑
          } else {
            // 当用户输入非正整数时，若要回到第一页，则放开下面两行代码
            // this.currentPageValue = 1
            // this.currentPage = 1
            console.log('error')
            // 代码逻辑
          }
        }
      }
    }
  </script>
  <style scoped>
    .colorRed{
        color:red;
    }
    .el-upload--text {
      width: 100%;
    }
    .btnflex{
      display: flex;
      justify-content: space-between;
    }
    .el-table th {
      padding: 0px 0;
      text-align: center;
      font-size: 12px;
      color: #333333;
      letter-spacing: 0;
    }
    .el-table td {
      padding: 0px 0;
      text-align: center;
      font-size: 2px;
      color: #333333;
      letter-spacing: 0;
    }
    #messBox {
      word-break: break-all;
    }
  </style>

